<?php

namespace app\admin\model;

use think\Model;

class Goods extends Model
{
    // 表名
    protected $name = 'goods';
    
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    
    // 追加属性
    protected $append = [
        'prom_type_text',
        'status_text',
        'category_id_text'
    ];
    

    protected static function init()
    {
        self::afterInsert(function ($row) {
            $pk = $row->getPk();
            $row->getQuery()->where($pk, $row[$pk])->update(['weigh' => $row[$pk]]);
        });


    }



    public function getList(){
        $list = $this->field('id,name')->order('id desc')->select();
        $data = [];
        foreach($list as $k => $v){
            $data[$v['id']] = $v['name'];
        }

        return $data;
    }
    
    public function getNoPromGoodsList(){
        $list = $this->where(['prom_type' => '0'])->field('id,name')->order('id desc')->select();
        $data = [];
        foreach($list as $k => $v){
            $data[$v['id']] = $v['name'];
        }

        return $data;
    }



    
    public function getPromTypeList()
    {
        return ['0' => __('Prom_type 0'),'1' => __('Prom_type 1'),'2' => __('Prom_type 2'),'3' => __('Prom_type 3'),'4' => __('Prom_type 4')];
    }     

    public function getStatusList()
    {
        return ['0' => __('Status 0'),'1' => __('Status 1')];
    }     


    public function getPromTypeTextAttr($value, $data)
    {        
        $value = $value ? $value : $data['prom_type'];
        $list = $this->getPromTypeList();
        return isset($list[$value]) ? $list[$value] : '';
    }


    public function getStatusTextAttr($value, $data)
    {        
        $value = $value ? $value : $data['status'];
        $list = $this->getStatusList();
        return isset($list[$value]) ? $list[$value] : '';
    }

    public function getCategoryIdTextAttr($value, $data)
    {
        $value = $value ? $value : $data['category_id'];
        $categoryM = new \app\common\model\Category();
        $list = $categoryM->getList('goods');
        return isset($list[$value]) ? $list[$value] : '';
    }

    public function saveProm($goods_id,$prom_type,$prom_id){
        Goods::where(['prom_type' => $prom_type, 'prom_id' => $prom_id])->update(['prom_type' => '0', 'prom_id' => 0]);
        $result = Goods::where(['id' => $goods_id])->update(['prom_type' => $prom_type, 'prom_id' => $prom_id]);
        return $result;
    }

    public function delProm($goods_id){
        Goods::where(['id' => $goods_id])->update(['prom_type' => '0', 'prom_id' => 0]);
    }






}
